package com.yishan.security.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yishan.security.config.RedisPrefix;
import com.yishan.security.domain.LoginUser;
import com.yishan.security.domain.User;
import com.yishan.security.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OncePerRequestFilter 请求前 只走一次
 *
 * @author: yishan
 * @Date: 2022/8/31 10:12
 **/
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1.获取header中的token
        String token = request.getHeader(RedisPrefix.TOKEN);
        if (StringUtils.isEmpty(token)) {
            //放行操作，之后后续过滤器
            filterChain.doFilter(request, response);
            return;
        }

        //2.解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException("token 不合法！");
        }

        //3.通过userId 去redis获取用户信息
        LoginUser loginUser = JSONObject.parseObject(stringRedisTemplate.opsForValue().get(RedisPrefix.LOGIN_USER + userId), LoginUser.class);
        log.info("当前登录用户={}", loginUser);
        if (ObjectUtils.isEmpty(loginUser)) {
            throw new RuntimeException("当前用户未登录！");
        }

        //4.封装Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

        //5.存入 SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //6.放行
        filterChain.doFilter(request, response);

    }
}
